package com.cctc.rds.nrpc.demo.rpc.impl;

import com.cctc.rds.nrpc.api.exception.RpcIOException;
import com.cctc.rds.nrpc.api.rpc.RpcRequest;
import com.cctc.rds.nrpc.api.rpc.RpcResponse;
import com.cctc.rds.nrpc.core.client.NettyRpcClient;
import com.cctc.rds.nrpc.demo.rpc.HelloRpc;
import com.cctc.rds.nrpc.demo.rpc.HelloRpcResponse;
import com.cctc.rds.nrpc.demo.rpc.HelloRpcReuqest;

public class HelloRpcRequestImpl implements HelloRpc {
    private NettyRpcClient client;

    public HelloRpcRequestImpl(NettyRpcClient client) {
        this.client = client;
    }


    @Override
    public HelloRpcResponse sum(HelloRpcReuqest reuqest) {
        RpcRequest rpcRequest = RpcRequest.builder()
                .interfaces(HelloRpc.class)
                .methodName("sum")
                .parameterTypes(new Class<?>[]{HelloRpcReuqest.class})
                .arguments(new Object[]{reuqest})
                .build();
        try {
            RpcResponse rpcResponse = client.remoteInvoke(rpcRequest);
            if (rpcResponse.getException() != null) {
                throw new RuntimeException(rpcResponse.getException());
            }
            return (HelloRpcResponse) rpcResponse.getResult();
        } catch (RpcIOException e) {
            throw new RuntimeException(e);
        }
    }
}
